package org.alicuu.dao;

import org.alicuu.toolkit.StringUtil;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Danny
 * Date: 16/07/06
 * Time: 19:27
 */
public class TableContext {

    static Map<Class, TableInfo> poClassTableMap = new HashMap<>();
    private static Map<String, TableInfo> tables = new HashMap<>();

    static {
        try {
            Connection conn = DBManager.getConnection();
            DatabaseMetaData metaData = conn.getMetaData();

            ResultSet tableMetaInfo = metaData.getTables(null, "%", "%", new String[]{"TABLE"});

            while (tableMetaInfo.next()) {
                String tableName = (String) tableMetaInfo.getObject("TABLE_NAME");
                TableInfo tableInfo = new TableInfo(tableName, new HashMap<>(), new ArrayList<>());
                tables.put(tableName, tableInfo);

                ResultSet columnsMeta = metaData.getColumns(null, "%", tableName, "%");
                while (columnsMeta.next()) {
                    String columnName = columnsMeta.getString("COLUMN_NAME");
                    ColumnInfo columnInfo = new ColumnInfo(columnName, columnsMeta.getString("TYPE_NAME"), 0);
                    tableInfo.getColumns().put(columnName, columnInfo);
                }


                ResultSet priKeySet = metaData.getPrimaryKeys(null, "%", tableName);
                while (priKeySet.next()) {
                    ColumnInfo columnInfo = (ColumnInfo) tableInfo.getColumns().get(priKeySet.getObject("COLUMN_NAME"));
                    columnInfo.setKeyType(ColumnInfo.PRIMARY_KEY);
                    tableInfo.getPrimaryKeys().add(columnInfo);
                }

                if (tableInfo.getPrimaryKeys().size() > 0)
                    tableInfo.setPrimaryKey(tableInfo.getPrimaryKeys().get(0));

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public TableContext() {
    }

    public static void updateJavaPOFile() {
        Map<String, TableInfo> map = tables;
        for (TableInfo tableInfo : map.values()) {
            try {
                Class clazz = Class.forName(DBManager.getConf().getPersistentObjPackage() + "." + StringUtil.firstCharUpperCase(tableInfo.getTableName()));
                poClassTableMap.put(clazz, tableInfo);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }


}
